﻿using System.Collections.Concurrent;
using Didaku.QEngine.Common.Abstracts.Entities;
using Didaku.QEngine.Common.Interfaces.Engine;

namespace Didaku.QEngine
{
    /// <summary>交易所涉及的卡片的存储与获取服务
    /// </summary>
    internal class CardService : ICardService
    {
        private readonly ConcurrentDictionary<string, CardInfo> _Map = new ConcurrentDictionary<string, CardInfo>();

        #region Implementation of ICardService

        /// <summary>是否需要持久化
        /// </summary>
        /// <value>
        ///   <c>true</c> if [require persistence]; otherwise, <c>false</c>.
        /// </value>
        public bool RequirePersistence
        {
            get { return true; }
        }

        /// <summary>尝试根据指定的卡片获取卡片
        /// </summary>
        /// <param name="number">The number.</param>
        /// <param name="cardInfo">The card info.</param>
        /// <returns></returns>
        public bool TryGet(string number, out CardInfo cardInfo)
        {
            return _Map.TryGetValue(number, out cardInfo);
        }

        /// <summary>增加一张卡片，如果该卡片已存在，将更新
        /// </summary>
        /// <param name="cardInfo">卡片.</param>
        /// <param name="needUpdate">当卡片已存在时，是否需要更新</param>
        /// <returns></returns>
        public CardInfo AddOrUpdate(CardInfo cardInfo, bool needUpdate = true)
        {
            return _Map.AddOrUpdate(cardInfo.CardNumber, cardInfo,
                                    (key, existingCard) =>
                                        {
                                            if (needUpdate) //是否需要更新
                                            {
                                                CardInfo removeData;
                                                _Map.TryRemove(key, out removeData);
                                                _Map.TryAdd(key, cardInfo);
                                            }
                                            return cardInfo;
                                        });
        }

        #endregion
    }
}